package com.zll.onlineExam.activities;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.zll.onlineExam.R;
import com.zll.onlineExam.ajax.Ajax;
import com.zll.onlineExam.ajax.HTTPConfig;
import com.zll.onlineExam.ajax.ReqCallback;
import com.zll.onlineExam.db.DBHelper;
import com.zll.onlineExam.entity.out.ArticleDtoOut;
import com.zll.onlineExam.entity.out.UserDtoOut;
import com.zll.onlineExam.utils.Base64Util;
import com.zll.onlineExam.utils.GlobalDataHolder;
import com.zll.onlineExam.utils.HtmlParser;
import com.zll.onlineExam.utils.StringUtil;
import com.zll.onlineExam.utils.XToastUtils;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ArticleContentActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView mBack;
    private ImageView mAvatar;
    private TextView mUsername;
    private TextView mTitle;
    private TextView mBonusTime;
    private TextView mBonusScore;
    private TextView mGain;
    private LinearLayout mArticleInfo;
    private LinearLayout mContent;
    private ImageOptions imageOptions;

    private static Handler mHandler;
    private Map<String, Object> parmas;

    private final int FETCH_SUCCESS = 1;
    private final int FETCH_FAIL = 0;
    private final int FETCH_ERROR = -1;
    private final int COMMIT_SUCCESS = 4;
    private final int COMMIT_GAIN = 5;
    private final int COMMIT_FAIL = 3;
    private final int COMMIT_ERROR = 2;
    private final int FLUSH_FAIL = 6;

    private static DataHolder mHolder;
    private static CountDownTimer timer;
    private SQLiteDatabase db;

    private static final String TAG = "===ArticleContent";

    private class DataHolder {
        private ArticleDtoOut data;

        public ArticleDtoOut getData() {
            return data;
        }

        public DataHolder setData(ArticleDtoOut data) {
            this.data = data;
            return this;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_content);
        imageOptions = new ImageOptions.Builder()
                // 如果ImageView的大小不是定义为wrap_content, 不要crop.
                .setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
                // 加载中或错误图片的ScaleType
                //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setPlaceholderScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.drawable.ic_default_head)
                .setFailureDrawableId(R.drawable.ic_default_head)
                .setIgnoreGif(false)
                .build();

        initView();
        initListener();
        initHandler();
        initData();

        db = DBHelper.getDB(this);
    }

    private void initHandler() {
        mHandler = new Handler() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case FETCH_SUCCESS:
                        loadData();
                        break;
                    case COMMIT_GAIN:
                        XToastUtils.info("获得积分+"+mHolder.getData().getBonusScore());
                        break;
                    case COMMIT_FAIL:
                        XToastUtils.info("已经获得积分");
                        break;
                    case FETCH_FAIL:
                        XToastUtils.error("获取失败");
                        break;
                    case FETCH_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    case FLUSH_FAIL:
                        XToastUtils.error("刷新用户信息失败");
                        break;
                    default:
                        break;
                }

            }
        };
    }

    private void initView() {
        mBack = findViewById(R.id.iv_back);
        mTitle = findViewById(R.id.a_de_title);
        mContent = findViewById(R.id.article_content_layout);
        mAvatar = findViewById(R.id.iv_avatar);
        mUsername = findViewById(R.id.tv_user_name);
        mBonusTime = findViewById(R.id.tv_bonus_time);
        mBonusScore = findViewById(R.id.tv_bonus_score);
        mArticleInfo = findViewById(R.id.article_info);
        mGain = findViewById(R.id.tv_gain);

    }

    private void initListener() {
        mBack.setOnClickListener(this);
    }

    private void initData() {
        mHolder = new DataHolder();
        String aid = getIntent().getStringExtra("aid");
        parmas = new HashMap<>();
        parmas.put("aid", aid);
        parmas.put("uid", GlobalDataHolder.getInstance().getCurUser().getUid());
        Ajax.post(HTTPConfig.LIST_ARTICLE, parmas, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                List<ArticleDtoOut> dtos = resp.getJSONArray("data").toJavaList(ArticleDtoOut.class);
                if (dtos.size() != 1){
                    mHandler.sendEmptyMessage(FETCH_FAIL);
                }else{
                    mHolder.setData(dtos.get(0));
                    mHandler.sendEmptyMessage(FETCH_SUCCESS);
                }
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FETCH_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            if (timer != null){
                Log.d(TAG, "timer cancel !");
                timer.cancel();
            }
            finish();
        }
    }

    /**
     * 获取到文章内容 渲染到页面
     */
    private void loadData(){
        mTitle.setText(mHolder.getData().getTitle());
        mUsername.setText(mHolder.getData().getPublisherUser().getNickname());
        x.image().bind(mAvatar,mHolder.getData().getPublisherUser().getAvatar(HTTPConfig.API+HTTPConfig.IMG_PREFIX),imageOptions);
        new HtmlParser(Base64Util.decode(mHolder.getData().getContent()),this).parseAndGen(mContent);

        mArticleInfo.setVisibility(View.VISIBLE);
        mBonusTime.setText(mHolder.getData().getBonusTime());
        mBonusScore.setText(mHolder.getData().getBonusScore());

        // 如果获得了积分就不考虑再次发请求确认积分
        if (mHolder.getData().getGainBonusScore() != 0){
            mGain.setVisibility(View.VISIBLE);
        }else{
            userReadArticle(false);
        }

        // 如果设置了奖励时间 且第一次进入 开始计时
        if (StringUtil.isNotBlank(mHolder.getData().getBonusTime()) && mHolder.getData().getGainBonusScore() == 0){
            Long totalSeconds = Long.parseLong(mHolder.getData().getBonusTime())*1000*60;
            timer = new CountDownTimer(totalSeconds,1000) {
                @Override
                public void onTick(long l) {}

                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onFinish() {
                    userReadArticle(true);
                }
            };
            timer.start();
            Log.d(TAG, "timer start: "+mHolder.getData().getBonusTime());
        }
    }

    /**
     * 用户进入页面后发起请求 记录阅读记录 完成时间后也调用该接口记录获得分数
     * @param gainScore 是否获得积分
     */
    private void userReadArticle(boolean gainScore) {
        parmas = new HashMap<>();
        String aid = getIntent().getStringExtra("aid");
        parmas.put("aid", aid);
        parmas.put("uid", GlobalDataHolder.getInstance().getCurUser().getUid());
        if (gainScore){
            parmas.put("gainBonusScore", mHolder.getData().getBonusScore());
        }else{
            parmas.put("gainBonusScore", 0);
        }
        Ajax.post(HTTPConfig.READ_ARTICLE, parmas, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                if(gainScore){
                    mHandler.sendEmptyMessage(COMMIT_GAIN);
                    getUserInfo();
                }
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(COMMIT_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }

    private void getUserInfo() {
        Ajax.post(HTTPConfig.FlUSH, new HashMap<>(), new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                GlobalDataHolder.getInstance().setCurUser(resp.getObject("data", UserDtoOut.class));
                DBHelper.initUser(db, resp.getObject("data", Map.class));
                Ajax.setToken(DBHelper.checkDBAndGetToken(db));
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FLUSH_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }
}